package cn.edu.scau.cmi.chenyuanying.classAdapter;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;

public class ClassAdapterController implements Initializable {
	@FXML Button insertButton;
	@FXML TextField idField;
	@FXML TextField nameField;
	@FXML TableView studentListTableView;
	@FXML TableColumn<Student, Integer> idColumn;
	@FXML TableColumn<Student, String> nameColumn;
	private ClassAdapterTarget studentList;
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		studentList = new AdapterOfClass();
		idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
		nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
		studentListTableView.setItems(studentList.students);
	}
	
	public void clickInsert(ActionEvent e) {
		String idStr = idField.getText();
		String nameStr = nameField.getText(); 
		if(nameStr == null || nameStr.equals("") || idStr == null || idStr.equals("")) {
			infoNotInput();
			return;
		}
		int id = idStrToInt(idStr);
		for(Student stu : studentList.students) {
			if(id == stu.getId()) {
				idExists();
				return;
			}
		}

		Student student = new Student(id, nameField.getText());
		studentList.insertStudent(student);		
	}
	
	public int idStrToInt(String idStr) {
		int id = 0, i = 0;
		while(i < idStr.length()) {
			id *= 10;
			id += idStr.charAt(i++) - '0';
		}
		return id;
	}
	
	public void infoNotInput() {
		Alert info = new Alert(Alert.AlertType.WARNING);
		info.setTitle("Warning");
		info.setHeaderText(null);
		info.setContentText("Please enter id and name.");
		info.show();
	}
	
	public void idExists() {
		Alert info = new Alert(Alert.AlertType.WARNING);
		info.setTitle("Warning");
		info.setHeaderText(null);
		info.setContentText("Id already exist!" + "\n" + "Ids should be unique!");
		info.show();
	}
	
	public void clearInputId(MouseEvent e) {
		idField.clear();
	}
	
	public void clearInputName(MouseEvent e) {
		nameField.clear();
	}
}
